# coding:UTF-8
# @Date:2018/7/12
# @Author:cxj
from tkinter import *
from tkinter import messagebox
import random,datetime
import xlsxwriter
import os
import time
from math import floor, ceil 
from tkinter.filedialog import askdirectory
import pathlib
from faker import Faker
from tkcalendar import DateEntry

fake = Faker("zh_CN")
def create_phone(): 
    # 第二位数字 
    second = [3, 4, 5, 7, 8][random.randint(0, 4)] 
    # 第三位数字 
    third = { 3: random.randint(0, 9), 
        4: [5, 7, 9][random.randint(0, 2)], 
        5: [i for i in range(10) if i != 4][random.randint(0, 8)], 
        7: [i for i in range(10) if i not in [4, 9]][random.randint(0, 7)], 
        8: random.randint(0, 9), }[second] 
    # 最后八位数字 
    suffix = random.randint(9999999,100000000) 
    # 拼接手机号 
    return "1{}{}{}".format(second, third, suffix) 
    # 生成手机号 
'''
排列顺序从左至右依次为：六位数字地址码，八位数字出生日期码，三位数字顺序码和一位校验码:
1、地址码 
表示编码对象常住户口所在县(市、旗、区)的行政区域划分代码，按GB/T2260的规定执行。
2、出生日期码 
表示编码对象出生的年、月、日，按GB/T7408的规定执行，年、月、日代码之间不用分隔符。 
3、顺序码 
表示在同一地址码所标识的区域范围内，对同年、同月、同日出生的人编定的顺序号，顺序码的奇数分配给男性，偶数分配给女性。 
4、校验码计算步骤
    (1)十七位数字本体码加权求和公式 
    S = Sum(Ai * Wi), i = 0, ... , 16 ，先对前17位数字的权求和 
    Ai:表示第i位置上的身份证号码数字值(0~9) 
    Wi:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 （表示第i位置上的加权因子）
    (2)计算模 
    Y = mod(S, 11)
    (3)根据模，查找得到对应的校验码 
    Y: 0 1 2 3 4 5 6 7 8 9 10 
    校验码: 1 0 X 9 8 7 6 5 4 3 2
'''
 
def getCheckBit(num17):
    """
    获取身份证最后一位，即校验码
    :param num17: 身份证前17位字符串
    :return: 身份证最后一位
    """
    Wi = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
    checkCode = ['1','0','X','9','8','7','6','5','4','3','2']
    zipWiNum17 = zip(list(num17),Wi)
    S = sum(int(i)*j for i,j in zipWiNum17)
    Y = S % 11
    return checkCode[Y]
 
def getAddrCode():
    """
    获取身份证前6位，即地址码
    :return: 身份证前6位
    """
    from addr import addr
    addrIndex = random.randint(0,len(addr)-1)
    return addr[addrIndex]
 
#def getBirthday(start="1991-01-02",end="1991-01-02"):
def getBirthday(start,end): #自定义出生日期
    """
    获取身份证7到14位，即出生年月日
    :param start: 出生日期合理的起始时间
    :param end: 出生日期合理的结束时间
    :return: 份证7到14位
    """
    days = (datetime.datetime.strptime(end,"%Y-%m-%d") - datetime.datetime.strptime(start,"%Y-%m-%d")).days + 1
    birthday = datetime.datetime.strptime(start,"%Y-%m-%d") + datetime.timedelta(random.randint(0,days))
    return datetime.datetime.strftime(birthday,"%Y%m%d")
 
def getRandomIdCard(start,end):
    """
    获取随机身份证
    :param sex: 性别，默认为男
    :return: 返回一个随机身份证
    """
    sex=1
    idNumber,addrName =  getAddrCode()
    idCode = str(idNumber) + getBirthday(start,end)
    for i in range(2):
        idCode += str(random.randint(0,9))
    idCode += str(random.randrange(sex,9,2))
    idCode += getCheckBit(idCode)
    return idCode
def createExcel(sj,path,check1,check2,check3,start,end): #选中是 1 否则为 0
        date=time.strftime('%Y%m%d',time.localtime(time.time()))
        if check1 ==1 and check2 ==1  and check3 ==1:
            workbook = xlsxwriter.Workbook(path+'\\手机号数据'+date+'.xlsx')  #创建一个Excel文件
            worksheet = workbook.add_worksheet()               #创建一个sheet
            title = [U'身份证',U'手机号',U'客户姓名']     #表格title
            worksheet.write_row('A1',title)                    #title 写入Excel
            print("身份证,手机号,客户姓名")
            f1=open(path+'\\手机号数据'+date+'.txt','w')
            f1.write('P_appntID,P_appntPhone,P_custName\n')
            for i in range(1,sj+1):
                num = str(i+1)
                row = 'A' + num
                data = [getRandomIdCard(start,end),create_phone(),fake.name().encode('unicode-escape').decode()]
                worksheet.write_row(row, data)
                f1.write(getRandomIdCard(start,end)+","+create_phone()+","+fake.name().encode('unicode-escape').decode()+'\n')
                i+=1
                print (getRandomIdCard(start,end)+","+create_phone()+","+fake.name().encode('unicode-escape').decode())
            workbook.close()
            f1.close()
            cMessage ="生成-身份证,手机号,客户姓名-【"+str(sj)+"】条数据完成！"
        elif check1 ==1 and check2 ==1 and check3 ==0:
            workbook = xlsxwriter.Workbook(path+'\\手机号数据'+date+'.xlsx')  #创建一个Excel文件
            worksheet = workbook.add_worksheet()               #创建一个sheet
            title = [U'身份证',U'手机号']     #表格title
            worksheet.write_row('A1',title)                    #title 写入Excel
            print("身份证，手机号")
            f1=open(path+'\\手机号数据'+date+'.txt','w')
            f1.write('P_appntID,P_appntPhone\n')
            for i in range(1,sj+1):
                num = str(i+1)
                row = 'A' + num
                data = [getRandomIdCard(start,end),create_phone()]
                worksheet.write_row(row, data)
                f1.write(getRandomIdCard(start,end)+","+create_phone()+'\n')
                i+=1
                print (getRandomIdCard(start,end)+","+create_phone()+'\n')
            workbook.close()
            f1.close()
            cMessage ="生成-身份证和手机号-【"+str(sj)+"】条数据完成！"
        elif check1 ==1 and check2 ==0 and check3 ==1:
            workbook = xlsxwriter.Workbook(path+'\\手机号数据'+date+'.xlsx')  #创建一个Excel文件
            worksheet = workbook.add_worksheet()               #创建一个sheet
            title = [U'身份证',U'客户姓名']     #表格title
            worksheet.write_row('A1',title)                    #title 写入Excel
            print("身份证,客户姓名")
            f1=open(path+'\\手机号数据'+date+'.txt','w')
            f1.write('P_appntID,P_custName\n')
            for i in range(1,sj+1):
                num = str(i+1)
                row = 'A' + num
                data = [getRandomIdCard(start,end),fake.name().encode('unicode-escape').decode()]
                worksheet.write_row(row, data)
                f1.write(getRandomIdCard(start,end)+","+fake.name().encode('unicode-escape').decode()+"\n")
                i+=1
                print (getRandomIdCard(start,end)+","+fake.name().encode('unicode-escape').decode())
            workbook.close()
            f1.close()
            cMessage ="生成-身份证和客户姓名-【"+str(sj)+"】条数据完成！"
        elif check1 ==0 and check2 ==1  and check3 ==1:
            workbook = xlsxwriter.Workbook(path+'\\手机号数据'+date+'.xlsx')  #创建一个Excel文件
            worksheet = workbook.add_worksheet()               #创建一个sheet
            title = [U'手机号',U'客户姓名']     #表格title
            worksheet.write_row('A1',title)                    #title 写入Excel
            print("手机号,客户姓名")
            f1=open(path+'\\手机号数据'+date+'.txt','w')
            f1.write('P_appntPhone,P_custName\n')
            for i in range(1,sj+1):
                num = str(i+1)
                row = 'A' + num
                data = [create_phone(),fake.name().encode('unicode-escape').decode()]
                worksheet.write_row(row, data)
                f1.write(create_phone()+","+fake.name().encode('unicode-escape').decode()+'\n')
                i+=1
                print (create_phone()+","+fake.name().encode('unicode-escape').decode())
            workbook.close()
            f1.close()
            cMessage ="生成-手机号,客户姓名-【"+str(sj)+"】条数据完成！"
        elif check1 ==1 and check2 ==0 and check3 ==0:
            workbook = xlsxwriter.Workbook(path+'\\手机号数据'+date+'.xlsx')  #创建一个Excel文件
            worksheet = workbook.add_worksheet()               #创建一个sheet
            title = [U'身份证']     #表格title
            worksheet.write_row('A1',title)                    #title 写入Excel
            print("身份证")
            f1=open(path+'\\手机号数据'+date+'.txt','w')
            f1.write('P_appntID\n')
            for i in range(1,sj+1):
                num = str(i+1)
                row = 'A' + num
                data = [getRandomIdCard(start,end)]
                worksheet.write_row(row, data)
                f1.write(getRandomIdCard(start,end)+"\n")
                i+=1
                print (getRandomIdCard(start,end))
            workbook.close()
            f1.close()
            cMessage ="生成-身份证号码-【"+str(sj)+"】条数据完成！"
        elif check1 ==0 and check2 ==1  and check3 ==0:
            workbook = xlsxwriter.Workbook(path+'\\手机号数据'+date+'.xlsx')  #创建一个Excel文件
            worksheet = workbook.add_worksheet()               #创建一个sheet
            title = [U'手机号']     #表格title
            worksheet.write_row('A1',title)                    #title 写入Excel
            print("手机号")
            f1=open(path+'\\手机号数据'+date+'.txt','w')
            f1.write('P_appntPhone\n')
            for i in range(1,sj+1):
                num = str(i+1)
                row = 'A' + num
                data = [create_phone()]
                worksheet.write_row(row, data)
                f1.write(create_phone()+'\n')
                i+=1
                print (create_phone())
            workbook.close()
            f1.close()
            cMessage ="生成-手机号-【"+str(sj)+"】条数据完成！"
        elif check1 ==0 and check2 ==0  and check3 ==1:
            workbook = xlsxwriter.Workbook(path+'\\手机号数据'+date+'.xlsx')  #创建一个Excel文件
            worksheet = workbook.add_worksheet()               #创建一个sheet
            title = [U'客户姓名']     #表格title
            worksheet.write_row('A1',title)                    #title 写入Excel
            print("客户姓名")
            f1=open(path+'\\手机号数据'+date+'.txt','w')
            f1.write('P_custName\n')
            for i in range(1,sj+1):
                num = str(i+1)
                row = 'A' + num
                data = [fake.name().encode('unicode-escape').decode()]
                worksheet.write_row(row, data)
                f1.write(fake.name().encode('unicode-escape').decode()+'\n')
                i+=1
                print (fake.name().encode('unicode-escape').decode())
            workbook.close()
            f1.close()
            cMessage ="生成-客户姓名-【"+str(sj)+"】条数据完成！"
        else:
            print('请选择要生成得参数类型')
            cMessage ='请选择要生成得参数类型'

        messagebox.showinfo("提示",cMessage)
def  framep():
            
    root =Tk()
    root.geometry('550x220') #设置窗口大小 
    root.title('生成身份证号码')
    v1=StringVar()
    v2=StringVar()
    v3=StringVar()
    v4=StringVar()
    v1.set(r'10') #设置文本框初始值
    v2.set(r'D:\\数据') #设置文本框初始值

    CheckVar1 = IntVar()
    CheckVar2 = IntVar()
    CheckVar3 = IntVar()
    
    CheckVar1.set(1)
    CheckVar2.set(1)
    CheckVar3.set(1)

    fm1=Frame(root,height=80,width=60,bd=5,borderwidth=1)
    fm1.pack(side=LEFT,fill=X,expand=False,pady=10,anchor=N)  #fill=NONE,expand=False,ipady=2
    fm2=Frame(root,height=80,width=60,bd=5,borderwidth=4)
    fm2.pack(side=LEFT,fill=X,expand=False,pady=10,anchor=N)
    fm3=Frame(root,height=80,width=60,bd=5,borderwidth=4)
    fm3.pack(side=LEFT,fill=X,expand=False,pady=10,anchor=N)
    lb1=Label(fm1,text="生成数据条数:",height=1,width=10,fg='red')
    lb1.pack(side=TOP, fill=X, expand=YES,pady=1)
    e1 = Entry(fm2,textvariable=v1,width=25,fg='red')
    e1.pack(side=TOP, fill=X, expand=YES,pady=1)
    lb2=Label(fm1,text="存放文件路径:",height=1,width=10,fg='red')
    lb2.pack(side=TOP, fill=X, expand=YES,pady=1)
    e2 = Entry(fm2,textvariable=v2,width=25,fg='red')
    e2.pack(side=TOP, fill=X, expand=YES,pady=1)
    def diaoyong():
        path = pathlib.Path(str(v2.get()))
        if path.exists()==False:
            print("目录不存在，即将创建！")
            os.mkdir(path)
        
        createExcel(int(v1.get()),str(v2.get()),CheckVar1.get(),CheckVar2.get(),CheckVar3.get(),str(cal.get_date()),str(cal.get_date()))
    def selectPath():
        filePath =askdirectory()
        if os.path.exists(filePath)==False:
           print("未选择目录！:【"+filePath+"】")
           #print(CheckVar1.get()) #选中是 1 否则为 0
        else:           
           print("选取的路径为："+filePath)
           v2.set(filePath)
    bt1 =Button(fm3,text='选存放文件路径',font=("楷书", 10, "bold"),height=1,width=15,fg='red',bg='pink',command=selectPath,relief="ridge")
    bt1.pack(side=TOP,fill=Y,expand=False,pady=1,anchor=N) #设置button 指定宽度并且关联函数 使用表格式布局 
    bt2 =Button(fm3,text='生成身份证号码',font=("楷书", 10, "bold"),height=1,width=15,fg='pink',bg='green',command=diaoyong,relief="ridge")
    bt2.pack(side=TOP,fill=Y,expand=False,pady=1,anchor=N) #设置button 指定宽度并且关联函数 使用表格式布局 

    Label(fm1,text="请勾选参数类型(可多选)",height=1,width=10,fg='red').pack(side=TOP, fill=X, expand=YES,pady=5)
    C1 = Checkbutton(fm1, text = "随机身份证号", variable = CheckVar1, \
                    onvalue = 1, offvalue = 0, height=2, \
                    width = 20)
    Label(fm2,text="  ",height=1,width=10,fg='red').pack(side=TOP, fill=X, expand=YES,pady=5)
    C2 = Checkbutton(fm2, text = "随机手机号码", variable = CheckVar2, \
                    onvalue = 1, offvalue = 0, height=2, \
                    width = 20)
    Label(fm3,text="2022年9月14日",height=1,width=10,fg='red').pack(side=TOP, fill=X, expand=YES,pady=5)
    C3 = Checkbutton(fm3, text = "随机中文姓名", variable = CheckVar3, \
                    onvalue = 1, offvalue = 0, height=2, \
                    width = 20)
    C4=Label(fm1,text="出生日期始终",height=1,width=10,fg='red')    
    C1.pack(side=TOP,fill=Y,expand=False,pady=5,anchor=N)
    C2.pack(side=TOP,fill=Y,expand=False,pady=6,anchor=N)
    C3.pack(side=TOP,fill=Y,expand=False,pady=4,anchor=N)
    C4.pack(side=TOP,fill=Y,expand=False,pady=1,anchor=N)
  
    cal = DateEntry(fm2, width=12, year=1990, month=1, day=1, 
    background='darkblue', foreground='white', borderwidth=2)
    cal.pack(padx=10, pady=10)
    cal1 = DateEntry(fm3, width=12, year=1990, month=1, day=1, 
    background='darkblue', foreground='white', borderwidth=2)
    cal1.pack(padx=10, pady=10)
    mainloop()

if __name__ == "__main__":
    framep()
